package com.dhh.nutrition.activity;

import greendroid.app.GDActivity;
import java.util.ArrayList;
import java.util.List;
import com.dhh.nutrition.R;
import com.dhh.nutrition.dao.DataBaseHelper;
import com.dhh.nutrition.manager.FoodManager;
import com.dhh.nutrition.vo.Food;
import com.dhh.nutrition.widget.AmazingAdapter;
import com.dhh.nutrition.widget.AmazingListView;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Pair;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;

public class SearchFoodActivity extends GDActivity {	
	private AmazingListView lsComposer;
	private SectionComposerAdapter adapter;
	private FoodManager fManager;
	private DataBaseHelper db;
	private ProgressDialog progressDialog;
	private String sFoodName;
	private String sGroupName;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setActionBarContentView(R.layout.result_search);
        
        db = new DataBaseHelper(getBaseContext());
        db.openDataBase();        
        fManager = new FoodManager(db);
        
        sFoodName = getIntent().getExtras().getString("sFoodName");
        sGroupName = getIntent().getExtras().getString("sFoodGroup");
    }
	
	@Override
	protected void onStart(){
		super.onStart();
		
		initActionBar();
		initView();
		showDialog(0);
	}
	
	@Override
	protected void onResume(){
		super.onResume();		
		
		SearchThread thread = new SearchThread();
		thread.start();
	}
	
	@Override
	protected void onPause(){
		super.onPause();
		if (db != null) {
			db.close();
		}
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		switch(id){
			case 0:
				progressDialog = new ProgressDialog(this);
				progressDialog.setTitle("Searching Food...");
				progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
				return progressDialog;			
		}
		
		return null;		
	}
	
	public void initActionBar(){
		getActionBar().setTitle("Search Result - " + sFoodName);
        getActionBar().setBackgroundColor(Color.rgb(154, 205, 50));
        getActionBar().getChildAt(0).
        	setOnClickListener(new OnClickListener(){
				@Override
				public void onClick(View v) {
					Intent intent = new Intent(SearchFoodActivity.this,HomeActivity.class);
					startActivity(intent);
				}});
	}
	
	public void initView(){
		lsComposer = (AmazingListView) findViewById(R.id.rs_lst);    
        lsComposer.setTextFilterEnabled(true);
		lsComposer.setDivider( null );
		lsComposer.setDividerHeight(1); 
		lsComposer.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
				TextView foodNo = (TextView) view.findViewById(R.id.lst_fd_no);
				Intent intent = new Intent(SearchFoodActivity.this,NutritionDetailActivity.class);
				intent.putExtra("foodNo",foodNo.getText().toString());
				startActivity(intent);				
			}
		});
	}
	
	class SectionComposerAdapter extends AmazingAdapter {
		private AsyncTask<Integer, Void, Pair<Boolean, List<Food>>> backgroundTask;
		private List<Food> list = new ArrayList<Food>();	
		
		public void reset() {
			if (backgroundTask != null) backgroundTask.cancel(false);
			
			list = fManager.getFoods(sGroupName,sFoodName.toString(), 1).second;
			notifyDataSetChanged();
		}

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public Food getItem(int position) {
			return list.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		protected void onNextPageRequested(int page) {			
			if (backgroundTask != null) {
				backgroundTask.cancel(false);
			}
			
			backgroundTask = new AsyncTask<Integer, Void, Pair<Boolean, List<Food>>>() {
				@Override
				protected Pair<Boolean, List<Food>> doInBackground(Integer... params) {
					int page = params[0];					
					return fManager.getFoods(sGroupName, sFoodName, page);
				}
				
				@Override
				protected void onPostExecute(Pair<Boolean, List<Food>> result) {
					if (isCancelled()) return; 
					
					list.addAll(result.second);
					nextPage();
					notifyDataSetChanged();
					
					if (result.first) {
						notifyMayHaveMorePages();
					} else {
						notifyNoMorePages();
					}
				};
			}.execute(page);
		}

		@Override
		public View getAmazingView(int position, View convertView, ViewGroup parent) {
			View res = convertView;
			if (res == null) res = getLayoutInflater().inflate(R.layout.list_food_item, null);
			TextView foodName = (TextView) res.findViewById(R.id.lst_fd_name);
			TextView foodNo = (TextView) res.findViewById(R.id.lst_fd_no);
			Food item = getItem(position);
			foodName.setText(item.getShrt_Desc());
			foodNo.setText(item.getNDB_No());
			return res;
		}

		@Override
		protected void bindSectionHeader(View view, int position, boolean displaySectionHeader) {
		}

		@Override
		public void configurePinnedHeader(View header, int position, int alpha) {
		}

		@Override
		public int getPositionForSection(int section) {
			return 0;
		}

		@Override
		public int getSectionForPosition(int position) {
			return 0;
		}

		@Override
		public Object[] getSections() {
			return null;
		}
		
		
	}
	
	private class SearchThread extends Thread {
        @Override
        public void run() {  
            handler.sendEmptyMessage(0);
        }

        private Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                displaySearchResults();
                progressDialog.dismiss();
            }
        };
    }
	
	private void displaySearchResults(){
		adapter = new SectionComposerAdapter();
		lsComposer.setLoadingView(getLayoutInflater().inflate(R.layout.loading_view, null));
		lsComposer.setDivider( null );
		lsComposer.setDividerHeight(1); 
		lsComposer.setAdapter(adapter);
		refreshList();
	}
	
	public void refreshList(){
		adapter.reset();
		
		if(adapter.getCount()==0){
			lsComposer.setVisibility(View.GONE);
		}else{
			lsComposer.setVisibility(View.VISIBLE);
			adapter.resetPage();
			adapter.notifyMayHaveMorePages();
		}		
	}	
}
